﻿Imports System.Net.Sockets
Imports System.Net
Imports System.Text

Public Class Form1

    Public intCurrentPort As Integer


    Public receivingUdpClient As UdpClient
    Public RemoteIpEndPoint As New  _
          System.Net.IPEndPoint(System.Net.IPAddress.Any, 0)
    Public ThreadReceive As System.Threading.Thread
    Dim SocketNO As Integer

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        txbQryIP.Text = My.Settings.IP
        txbQryPort.Text = My.Settings.Port

    End Sub

    Enum MsgType
        MsgByte
        MsgString
    End Enum

    Private Sub UpdateQueryLog(ByVal NewMessage As Object, Optional ByVal MsgType As MsgType = MsgType.MsgString)
        Select Case MsgType
            Case Form1.MsgType.MsgByte
                Dim BitDet As Byte() = NewMessage
                Dim tempStr2 As String = ""
                Dim tempStr As String = ""
                Dim i As Int16 = 0
                Dim line As Int16 = 0
                Dim result As String = ""
                For j = 0 To BitDet.Length - 1
                    If BitDet(j) = True Then
                        Console.Write("1 ")
                        tempStr2 = tempStr
                        tempStr = " 1" + tempStr2
                    Else
                        Console.Write("0 ")
                        tempStr2 = tempStr
                        tempStr = " 0" + tempStr2
                    End If
                    i += 1
                    If i = 8 And j <= (BitDet.Length - 1) Then
                        line += 1
                        i = 0
                        result = result + tempStr
                        tempStr = ""
                        tempStr2 = ""
                        result = result + vbCrLf
                        If j <> (BitDet.Length - 1) Then
                            result = result + line.ToString & ") "
                            txbQryLog.Text = FormatDateTime(Now, DateFormat.ShortTime) & " - " & result & vbNewLine & txbQryLog.Text
                        End If
                    End If
                Next
            Case Else

        End Select
        txbQryLog.Text = FormatDateTime(Now, DateFormat.ShortTime) & " - " & NewMessage & vbNewLine & txbQryLog.Text
    End Sub

    Private Sub btnServerQuery_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnServerQuery.Click
        Try
            My.Settings.IP = txbQryIP.Text
            My.Settings.Port = txbQryPort.Text

            'Dim intPort As Integer = txbPort.Text
            'If intPort = "" Then MsgBox("Please update the config page and try again") : Exit Sub

            Dim udpClient As New UdpClient

            Dim GLOIP As IPAddress = IPAddress.Parse(txbQryIP.Text)
            Dim GLOINTPORT As Integer = txbQryPort.Text
            Dim bytCommand As Byte() = New Byte() {}

            Try
                udpClient.Connect(GLOIP, GLOINTPORT)
            Catch ex As Exception
                udpClient.Client.Close()
                udpClient.Connect(GLOIP, GLOINTPORT)
            End Try

            bytCommand = Encoding.ASCII.GetBytes(";þý.CORYÿÿ.")
            Dim pRet As Integer = udpClient.Send(bytCommand, bytCommand.Length)
            UpdateQueryLog("No of bytes send " & pRet)

            'ThreadReceive = _
            '   New System.Threading.Thread(AddressOf ReceiveMessages)
            'ThreadReceive.Start()
        Catch ex As Exception
            UpdateQueryLog(ex.Message)
        End Try
    End Sub

    Private Sub bwpReceiveUDP_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bwpReceiveUDP.DoWork
        bwpReceiveUDP.ReportProgress(0, "Waiting for reply")
        SocketNO = CInt(txbQryPort.Text)
        receivingUdpClient = New System.Net.Sockets.UdpClient(SocketNO)
        Dim receiveBytes As [Byte]() = receivingUdpClient.Receive(RemoteIpEndPoint)
        'txtIP.Text = RemoteIpEndPoint.Address.ToString
        Dim BitDet As BitArray
        BitDet = New BitArray(receiveBytes)
        Dim strReturnData As String = System.Text.Encoding.Unicode.GetString(receiveBytes)
        bwpReceiveUDP.ReportProgress(0, strReturnData)
        receivingUdpClient.Close()

        '        UpdateQueryLog(strReturnData, MsgType.MsgByte)
    End Sub


    Private Sub bwpReceiveUDP_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bwpReceiveUDP.ProgressChanged
        UpdateQueryLog(e.UserState)
    End Sub

    Private Sub tmrBWP_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrBWP.Tick
        If bwpReceiveUDP.IsBusy Then
            lblStatus.BackColor = Color.Red
        Else
            lblStatus.BackColor = Color.Green

            'receive the reply
            If Not bwpReceiveUDP.IsBusy Then
                intCurrentPort = My.Settings.Port
                bwpReceiveUDP.RunWorkerAsync()
            End If
        End If
    End Sub

    Private Sub btnReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReset.Click
        My.Settings.Port = txbQryPort.Text

        'Dim intPort As Integer = txbPort.Text
        'If intPort = "" Then MsgBox("Please update the config page and try again") : Exit Sub

        Dim udpClient As New UdpClient

        Dim GLOIP As IPAddress = IPAddress.Parse("127.0.0.1")
        Dim GLOINTPORT As Integer = intCurrentPort
        Dim bytCommand As Byte() = New Byte() {}

        Try
            udpClient.Connect(GLOIP, GLOINTPORT)
        Catch ex As Exception
            udpClient.Client.Close()
            udpClient.Connect(GLOIP, GLOINTPORT)
        End Try

        bytCommand = Encoding.ASCII.GetBytes("RESET UDP")
        Dim pRet As Integer = udpClient.Send(bytCommand, bytCommand.Length)
        UpdateQueryLog("No of bytes send " & pRet)

    End Sub
End Class
